package com.world.rickcloudendpoint.common;

import com.alibaba.fastjson.JSON;

/**
 * @description: 统一API响应结果封装
 * @author: jlsong
 * @date: 2021/12/30 22:35:53
 * @version: 1.0
 */
public class Result<T> {
    private int code;
    private String message;
    private T data;

    /**
     * 构造方法私有化，不允许外部new Result
     *
     * @param resultCode
     */
    private Result(ResultCode resultCode) {
        if (null == resultCode) {
            return;
        }
        this.code = resultCode.code();
        this.message = resultCode.msg();
    }

    /**
     * 构造方法私有化，不允许外部new Result
     *
     * @param data 数据
     */
    private Result(T data) {
        this.code = ResultCode.SUCCESS.code();
        this.message = ResultCode.SUCCESS.msg();
        this.data = data;
    }

    /**
     * 成功时
     *
     * @param <T>
     * @return
     */
    public static <T> Result<T> ok(T data) {
        return new Result<T>(data);
    }

    /**
     * 失败
     *
     * @param <T>
     * @return
     */
    public static <T> Result<T> fail(ResultCode resultCode) {
        return new Result<T>(resultCode);
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public Result setCode(int code) {
        this.code = code;
        return this;
    }

    public Result setMessage(String message) {
        this.message = message;
        return this;
    }

    public T getData() {
        return data;
    }

    public Result setData(T data) {
        this.data = data;
        return this;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
